<template>
  <div class="role">
    <el-card>
      <el-form inline>
        <el-row>
          <el-col :span="6">
            <el-form-item label="职位搜索">
              <el-input placeholder="请输入职位" v-model="keyword" />
            </el-form-item>
          </el-col>

          <el-col :span="4" style="margin-left: auto">
            <el-form-item>
              <el-button type="primary" size="default" @click="search" :disabled="!keyword.length">搜索</el-button>
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card style="margin: 10px 0">
      <el-button type="primary" icon="Plus" size="default" @click="beforeAddRole">添加职位</el-button>

      <el-table border :data="records" style="margin: 10px 0" v-loading="loading">
        <el-table-column type="index" label="#" align="center" />
        <el-table-column label="ID" prop="id" />
        <el-table-column label="角色名称" show-overflow-tooltip prop="roleName" />
        <el-table-column label="创建时间" show-overflow-tooltip prop="createTime" />
        <el-table-column label="更新时间" show-overflow-tooltip prop="updateTime" />
        <el-table-column label="操作" width="300">
          <template #="{ row }">
            <el-button type="primary" icon="User" size="small" @click="beforeAssignRole(row)" v-loading="row.assignLoading">分配权限</el-button>
            <el-button type="info" icon="Edit" size="small" @click="beforeEidt(row)">编辑</el-button>
            <el-popconfirm :title="`是否确定删除该${row.roleName}吗？`" confirmButtonText="确定" cancelButtonText="取消" @confirm="deleteRole(row)">
              <template #reference>
                <el-button type="danger" icon="Delete" title="删除" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:currentPage="pageNo"
        v-model:page-size="limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="prev, pager, next, jumper, ->,sizes, total"
        @current-change="getHasRole"
        @size-change="sizeChange"
        :total="total"
        background
      />
    </el-card>

    <!-- 新增编辑弹窗 -->
    <addOrEditRole ref="addOrEditRoleRef" @reload="$event = $event ? getHasRole(pageNo) : getHasRole()" />
    <!-- 分配角色抽屉 -->
    <assignRoleDrawer ref="assignRoleDrawerRef" @reload="reloadAssignRole" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, nextTick } from 'vue'
  import { reqAllRoleList, reqRemoveRole } from '@/api/acl/role'
  import { RoleResponseData, Records, RoleData } from '@/api/acl/role/type'
  import { getElMessage } from '@/utils/message'
  import useLayoutSettingStore from '@/store/modules/setting'
  import addOrEditRole from './components/addOrEditRole.vue'
  import assignRoleDrawer from './components/assignRoleDrawer.vue'

  const pageNo = ref<number>(1)
  const limit = ref<number>(10)
  const total = ref<number>(0)
  const keyword = ref<string>('')
  const records = ref<Records>([])
  const loading = ref<boolean>(false)
  const addOrEditRoleRef = ref<InstanceType<typeof addOrEditRole>>()
  const assignRoleDrawerRef = ref<InstanceType<typeof assignRoleDrawer>>()
  onMounted(() => {
    getHasRole()
  })

  async function getHasRole(pager = 1) {
    pageNo.value = pager
    try {
      loading.value = true
      const res: RoleResponseData = await reqAllRoleList(pageNo.value, limit.value, keyword.value)
      if (res.code === 200) {
        records.value = res.data.records.map((o) => {
          o.assignLoading = false
          return o
        })
        total.value = res.data.total
      } else {
        getElMessage('获取职位列表失败', 'error')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    } finally {
      loading.value = false
    }
  }

  // 点击新增按钮
  function beforeAddRole() {
    addOrEditRoleRef.value?.open({})
    nextTick(() => {
      addOrEditRoleRef.value?.formRef?.resetFields()
    })
  }

  // 点击编辑按钮
  function beforeEidt(row: RoleData) {
    addOrEditRoleRef.value?.open(row)
    nextTick(() => {
      addOrEditRoleRef.value?.formRef?.resetFields()
    })
  }

  // 点击分配角色按钮
  function beforeAssignRole(row: RoleData) {
    assignRoleDrawerRef.value?.open(row)
  }

  // 点击删除按钮
  async function deleteRole(row: RoleData) {
    try {
      const res: any = await reqRemoveRole(row.id as number)
      if (res.code === 200) {
        getElMessage('删除成功', 'success')
      } else {
        getElMessage('删除失败', 'error')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    } finally {
      getHasRole(records.value.length ? pageNo.value - 1 : pageNo.value)
    }
  }

  function reloadAssignRole() {
    window.location.reload()
  }

  // 搜索
  function search() {
    getHasRole()
    keyword.value = ''
  }

  // 重置
  const settingStore = useLayoutSettingStore()
  function reset() {
    settingStore.refresh = !settingStore.refresh
  }

  function sizeChange() {
    getHasRole()
  }
</script>

<style lang="scss" scoped></style>
